package com.examination.controller.utils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Auther: GongXl
 * @Date: 016 17:58
 * @Description:
 */
@WebServlet("/EmailWebServlet")
public class EmailWebServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        String emailStr = request.getParameter("emailStr");
        String findSeq = "-1";
        // 设置响应内容类型
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        List list = getMailsByWeb();
        StringBuffer sb = new StringBuffer();

        for (int i = 0; i < list.size(); i++) {
            sb.append("<br/>");
            if(null != emailStr && emailStr.equals(list.get(i))){
                sb.append("<font color='red'>"+(i+1)+" "+list.get(i)+"</font>");
                findSeq = i+1+"";
            }else{
                sb.append((i+1)+" "+list.get(i));
            }

        }
        String docType = "<!DOCTYPE html>\n";
        out.println(docType +
                "<html>\n" +
                "<head><title>邮箱爬取测试</title></head>\n" +
                "<body bgcolor=\"#f0f0f0\">" +
                "要找的email:"+emailStr+" 序号："+findSeq+
                        sb.toString()+
                "</body></html>");
    }
    private static List<String> getMailsByWeb() throws IOException {
        /*
         * 网页爬虫：其实是一个程序用于在互联网中去获取复合制定规则的数据
         * 爬取网页中的邮箱地址
         */
        List<String> list=new ArrayList<>();
//1.读取原文件
        URL url=new URL("http://blog.sina.com.cn/s/blog_515617e60101e151.html");
        BufferedReader br=new BufferedReader(new InputStreamReader(url.openStream()));
//2.对读取的数据进行规则匹配，从中获取符合规则的数据。
        String mail_regex="\\w+@\\w+(\\.[A-Za-z]{2,3})+";
        Pattern p=Pattern.compile(mail_regex);
        String line=null;

//3.将符合规则的数据存入集合。
        while((line=br.readLine())!=null){
            Matcher m=p.matcher(line);//读取一行，匹配一行
            while(m.find()){
                list.add(m.group());
            }
        }
        return list;
    }

}